package com.rslai.commons.http.tools;

import org.apache.http.conn.ssl.SSLSocketFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * SSL 有效性检查
 */
class X509TrustManagerImpl implements X509TrustManager {
    /**
     * 忽略客户端 SSL 检查
     *
     * @param x509Certificates
     * @param s
     * @throws CertificateException
     */
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    /**
     * 忽略服务器 SSL 检查
     *
     * @param x509Certificates
     * @param s
     * @throws CertificateException
     */
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

/**
 * SSL工厂类
 */
public class SSLFactory {

    /**
     * 创建一个忽略 SSL 检查的 SSLSocketFactory
     *
     * @return SSLSocketFactory
     */
    public static SSLSocketFactory getIgnoreSSLCheckSocketFactory() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            TrustManager[] trustManagers = new TrustManager[]{new X509TrustManagerImpl()};
            ctx.init(null, trustManagers, null);
            return new SSLSocketFactory(ctx);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}
